package com.hsy.bibc.modules.my.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.widget.DPCircleImageView;
import com.deparse.dpframe.utils.DPFileUtil;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPImageUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.deparse.dpframe.utils.DPToastUtil;
import com.deparse.dpframe.utils.DPUnitUtil;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.common.gsondata.ImageUploadResponseData;
import com.hsy.bibc.modules.my.gsondata.MyInfoGsonData;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.R;
import com.hsy.bibc.utils.HttpUtil;
import com.hsy.bibc.utils.VolleyLoadPicture;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2016/4/7.
 */
public class MyInformationActivity extends CommonBaseActivityWithSimpleActionBar {
    public static final String TITLE = "title";
    private RelativeLayout nick_relative, company_relative, head_relative, contact_relative;
    private ImageView avatar;
    private TextView nickname, company_name, contact_name;
    private String sexString;
    private String photoSaveFile;
    private AlertDialog sexDialog;
    private ArrayList<String> imagesSelected = new ArrayList<>();
    private DPHttpUtil.HttpCallback callback = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                MyInfoGsonData.Result result = DPGsonUtil.fromJson(response, MyInfoGsonData.Result.class);
                showUI(result);
                CommonUtils.hideProgressDialog();
            }
            if (1 == what) {
                sexDialog.dismiss();
                showToast(R.string.msg_change_success);
                getHttp();
            }
            if (2 == what) {
                showToast(R.string.post_image_success);
                CommonUtils.hideUploadProgressDialog();
//                    JSONObject result=new JSONObject(response);
                VolleyLoadPicture vlp = new VolleyLoadPicture(MyInformationActivity.this, avatar);
                vlp.getmImageLoader().get(response, vlp.getOne_listener());

//                DPPicassoUtil.with(MyInformationActivity.this).load(DPFileUtil.FILE_PREFIX + imagesSelected.get(0)).resize(DPUnitUtil.dip2px(MyInformationActivity.this, 40f), DPUnitUtil.dip2px(MyInformationActivity.this, 40f)).into(avatar);
            }

        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            CommonUtils.hideProgressDialog();
            if (2 == what) {
                showToast(R.string.msg_post_image_failure);
                CommonUtils.hideUploadProgressDialog();
            }
        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            CommonUtils.hideProgressDialog();
            if (2 == what) {
                showToast(R.string.msg_post_image_failure);
                CommonUtils.hideUploadProgressDialog();
            }
        }
    };
    private String postAvatar;
    private static final int MSG_UPDATE_AVATAR = 0x8001;
    private static final int MSG_UPDATE_AVATAR1 = 0x8002;

    private void showUI(MyInfoGsonData.Result result) {
        nickname.setText(result.getName());
        company_name.setText(result.getMerchant());
        contact_name.setText(result.getPhone());
//        if (result.getSex().equals("1")) {
//            sexString = "男";
//            sex.setText("男");
//        } else {
//            sexString = "女";
//            sex.setText("女");
//        }
//        DPPicassoUtil.with(this).load(result.getLogo()).into(avatar);
        VolleyLoadPicture vlp = new VolleyLoadPicture(this, avatar);
        vlp.getmImageLoader().get(result.getLogo(), vlp.getOne_listener());
    }

    @Override
    protected void onResume() {
        super.onResume();
        getHttp();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.title_my_information);
        setTitleTextColor(R.color.tab_text_color_normal);
        setContentView(R.layout.activity_change_person_information);

        nick_relative = F(R.id.nick_relative);
        company_relative = F(R.id.company_relative);
        head_relative = F(R.id.head_relative);
        contact_relative = F(R.id.contact_relative);

        avatar = F(R.id.avatar);
        nickname = F(R.id.nickname);
        company_name = F(R.id.company_name);
        contact_name = F(R.id.contact_name);

        nick_relative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MyInformationActivity.this, MyCommonEditActivity.class);
                intent2.putExtra(TITLE, "修改昵称");
                intent2.putExtra("name", nickname.getText().toString());
                startActivity(intent2);
            }
        });
        company_relative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent2 = new Intent(MyInformationActivity.this, MyCommonEditActivity.class);
//                intent2.putExtra(TITLE, "修改公司名");
//                startActivity(intent2);
            }
        });

//        sex_relative.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showSexDialog(sexString);
//            }
//        });
        head_relative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showImageSelectDialog(MyInformationActivity.this, null, new CommonUtils.ImageSelectDialogDismissListener() {
                    @Override
                    public boolean onDismiss(int type) {
                        if (type == CommonUtils.TYPE_FROM_CAMERA) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File file = DPFileUtil.makeCacheFile(MyInformationActivity.this, Consts.CACHE_DIR_PUB_ACT, System.currentTimeMillis() + ".jpg");
                            photoSaveFile = file.getAbsolutePath();
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            startActivityForResult(intent, Consts.REQ_TAKE_PICTURES);
                            return true;
                        }
                        return false;
                    }
                }, "true");
            }
        });
//        contact_relative.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent2 = new Intent(MyInformationActivity.this, MyCommonEditActivity.class);
//                intent2.putExtra(TITLE, "修改联系电话");
//                intent2.putExtra("name", contact_name.getText().toString());
//                startActivity(intent2);
//            }
//        });
    }

    private void getHttp() {
        CommonUtils.showProgressDialog(this);
        HttpUtil.httpGet(this, 0, Consts.API_GET_MY_INFO, callback);
    }

//    private void postSexHttp(int sex) {
//        Map<String, String> data = new HashMap<>();
//        data.put("msg", String.valueOf(sex));
//        HttpUtil.httpPostWithParams(this, 1, Consts.API_GET_MY_CHANGE_SEX, data, callback);
//    }

    private void postAvatarHttp(String avatar) {
        DPLogUtil.d("post image success");
        Map<String, String> data = new HashMap<>();
        data.put("msg", avatar);
        HttpUtil.httpPostWithParams(this, 2, Consts.API_POST_MY_CHANGE_AVATAR, data, callback);
    }

    public void showSexDialog(String sex) {
        sexDialog = new AlertDialog.Builder(MyInformationActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.head_dialog, (ViewGroup) findViewById(R.id.dialog_parent));
//        builder.setView(layout);
        sexDialog.show();
        sexDialog.setCancelable(true);
        sexDialog.getWindow().setContentView(layout);

        RadioGroup dialog_parent = (RadioGroup) layout.findViewById(R.id.dialog_parent);
        RadioButton man = (RadioButton) layout.findViewById(R.id.man);
        RadioButton woman = (RadioButton) layout.findViewById(R.id.woman);

        if (sex.equals("男")) {

            man.setChecked(true);
        } else {

            woman.setChecked(true);
        }

//        dialog_parent.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (checkedId == R.id.man) {
//                    postSexHttp(1);
//                } else {
//                    postSexHttp(2);
//                }
//            }
//        });
    }

    private void postImage() {
        DPLogUtil.e("imagesSelected.size()" + imagesSelected.size());
        DPLogUtil.e("imagesSelected[0]" + imagesSelected.get(0));

        if (null != imagesSelected && 0 < imagesSelected.size()) {
            AsyncTask<String, Integer, String> task = new AsyncTask<String, Integer, String>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    CommonUtils.showUploadProgressDialog(MyInformationActivity.this);
                }

                @Override
                protected String doInBackground(String... args) {
                    RequestParams params = new RequestParams();
                    File[] files = new File[imagesSelected.size()];
                    for (int i = 0; i < imagesSelected.size(); i++) {
                        String path = CommonUtils.getImageCacheDir(MyInformationActivity.this) + System.currentTimeMillis() + ".jpg";
                        files[i] = DPFileUtil.makeCacheFile(MyInformationActivity.this, path);
                        DPImageUtil.saveBitmapToFile(DPImageUtil.compressBySizeAndQuality(DPImageUtil.getBitmapFromFile(imagesSelected.get(i))), files[i]);
                        DPLogUtil.d("file[" + i + "].size=" + (files[i].exists() ? files[i].length() : 0) / 1024);
                    }
                    try {
                        params.put("imgs[]", files);
                        params.put(Consts.TOKEN, CommonUtils.getToken(MyInformationActivity.this));
                        DPHttpUtil.uploadFiles(Consts.API_UPLOAD_IMAGES, params, new AsyncHttpResponseHandler(MyInformationActivity.this.getMainLooper()) {
                            @Override
                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                if (null == bytes) {
                                    return;
                                }
                                DPLogUtil.d("yyy " + new String(bytes));

                                String response = new String(bytes);
                                ImageUploadResponseData data = DPGsonUtil.fromJson(response, ImageUploadResponseData.class);
                                DPLogUtil.d("yyy " + data.getError());
                                if (!"0".equals(data.getError())) {
//                                    showToast(data.getMsg());
                                    sendEmptyMessage(MSG_UPDATE_AVATAR);
//                                    DPLogUtil.d(data.getMsg());
                                    CommonUtils.hideUploadProgressDialog();
                                    return;
                                }

                                postAvatar = data.getResult().get(0);
                                postAvatarHttp(postAvatar);
                            }

                            @Override
                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                                DPLogUtil.e(new String(bytes));

                                sendEmptyMessage(MSG_UPDATE_AVATAR1);
                                CommonUtils.hideUploadProgressDialog();
                            }
                        });
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    CommonUtils.hideProgressDialog();
                }
            };
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }


//        File file = new File(imagesSelected.get(0));
//        for (int i = 0; i < imagesSelected.size(); i++) {
//            String path = CommonUtils.getImageCacheDir(this) + System.currentTimeMillis() + ".jpg";
//            files[i] = DPFileUtil.makeCacheFile(this, path);
//            DPImageUtil.saveBitmapToFile(DPImageUtil.compressBySizeAndQuality(DPImageUtil.getBitmapFromFile(imagesSelected.get(i))), files[i]);
//            DPLogUtil.d("file[" + i + "].size=" + (files[i].exists() ? files[i].length() : 0) / 1024);
//        }
//        try {
//            params.put("imgs[]", files);
//            params.put(Consts.TOKEN, CommonUtils.getToken(MyInformationActivity.this));
//            CommonUtils.showProgressDialog(this);
//            DPHttpUtil.uploadFiles(Consts.API_UPLOAD_IMAGES, params, new AsyncHttpResponseHandler() {
//                @Override
//                public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                    if (null == bytes) {
//                        return;
//                    }
//                    DPLogUtil.d("yyy " + new String(bytes));
//                    String response = new String(bytes);
//
//                    try {
//                        JSONObject data = new JSONObject(response);
//                        String result = data.optString("result");
//
//                        postAvatar = result;
//
//                        String error = data.optString("error");
//
//                        String msg = data.optString("msg");
//
//                        DPLogUtil.d(result);
//
//                        if (!"0".equals(error)) {
//                            showToast(msg);
//                            CommonUtils.hideProgressDialog();
//                            return;
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                    postAvatarHttp(postAvatar);
//                }
//
//                @Override
//                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                    DPLogUtil.e("onFailure上传first失败");
//                    if (bytes == null) {
//                        DPLogUtil.e("bytes==null");
//                    } else {
//                        DPLogUtil.e(new String(bytes));
//                    }
//                    showToast(R.string.msg_post_image_failure);
//                    CommonUtils.hideProgressDialog();
//
//                    DPLogUtil.e("throwable.getMessage()=" + throwable.getMessage() + "throwable.getMessage().toString()" + throwable.getMessage().toString());
//                }
//            });
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            DPLogUtil.e("e.getMessage()=" + e.getMessage());
//        }

    }

    @Override
    protected void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (MSG_UPDATE_AVATAR == msg.what) {
            showToast("此照片不可作为头像!");
        }
        if (MSG_UPDATE_AVATAR1 == msg.what) {
            DPToastUtil.showToast(MyInformationActivity.this, R.string.txt_network_failure);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DPLogUtil.enter("requestCode=" + requestCode + ",resultCode=" + resultCode + ",data=" + (null == data ? "null" : data.toString()));
        if (requestCode == Consts.REQ_SELECT_IMAGES && resultCode == MultiImageSelectorActivity.RESULT_OK) {
            if (null == data) {
                return;
            }
            imagesSelected.clear();
            List<String> paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if (null == paths) {
                return;
            }
            for (String path : paths) {
                if (null == path) {
                    continue;
                }
                imagesSelected.add(path);
            }
            postImage();


        } else if (requestCode == Consts.REQ_TAKE_PICTURES) {
            if (RESULT_OK == resultCode) {
                File file = new File(photoSaveFile);
                if (file.exists()) {
                    try {
                        MediaStore.Images.Media.insertImage(getContentResolver(), photoSaveFile, file.getName(), file.getAbsolutePath());
                        MediaScannerConnection.scanFile(this, new String[]{photoSaveFile}, null, null);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    imagesSelected.clear();
                    imagesSelected.add(file.getAbsolutePath());
                } else {
                    showToast(R.string.failed_to_take_photo);
                }

                postImage();


            } else {
                showToast(R.string.failed_to_take_photo);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File file = new File(DPFileUtil.getCacheDir(this, Consts.CACHE_DIR_PUB_ACT));
        if (file.exists()) {
            file.delete();
        }
    }
}
